package com.controller;


import com.util.BaseDao;
import com.util.StringUtil;
import javafx.fxml.FXML;
import javafx.scene.control.*;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import static com.Main.changeUI;

public class Regist {
    @FXML
    private TextField userId;

    @FXML
    private TextField userName;

    @FXML
    private PasswordField fpassword;

    @FXML
    private PasswordField ensurePassword;

    @FXML
    private Label errorInfo;

    @FXML
    public void dosubmit() {
        String userid = userId.getText();
        String username = userName.getText();
        String password = fpassword.getText();
        String confirmPassword = ensurePassword.getText();
        if(StringUtil.isEmpty(userid)){
            errorInfo.setText("请输入用户ID！");
            errorInfo.setVisible(true);
            return;
        }
        if(StringUtil.isEmpty(username)){
            errorInfo.setText("请输入用户名！");
            errorInfo.setVisible(true);
            return;
        }
        if(StringUtil.isEmpty(password) ||
                StringUtil.isEmpty(confirmPassword)){
            errorInfo.setText("密码不能为空！");
            errorInfo.setVisible(true);
        }else if(!password.equals(confirmPassword)){
            errorInfo.setText("密码错误！");
            errorInfo.setVisible(true);
            }else {
            Connection conn = null;
            PreparedStatement ps = null;
            try {
                conn = BaseDao.getConn(); // 假设这个方法返回一个有效的数据库连接
                String sql = "INSERT INTO Logon (wno, aname, password) VALUES (?, ?, ?) ";
                try {
                    ps = conn.prepareStatement(sql);
                    ps.setString(1,userid);
                    ps.setString(2,confirmPassword);
                    ps.setString(3,username);//预处理语句可以提高效率，防止SQL注入攻击使用占位符允许你使用不同的参数值来执行相同的SQL语句

                    int affectedRows = ps.executeUpdate();
                    if(affectedRows > 0){
                        System.out.println("数据插入成功！");
                    }else {
                        System.out.println("数据插入失败！");
                    }
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            } catch (RuntimeException e) {
                throw new RuntimeException(e);
            }
        }
            Alert successAlert = new Alert(Alert.AlertType.INFORMATION, "注册成功，请登录！", ButtonType.OK);
            successAlert.showAndWait().ifPresent(response -> {
                if (response == ButtonType.OK) {
                    // 用户点击"确定"后执行的操作
                    changeUI("ui/login.fxml");
                }
        });
    }
}
